package mips.instructions;

import mips.Main;

/**
 * <code>J</code> instruction<br/>
 * Jump<br/>
 * @author jnmartin84@gmail.com
 */
public class J extends Instruction {

	private static final J INSTANCE = new J();
	private static final String INSTRUCTION_NAME = "J";

	private J(){}

	public static final J getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * J target<br/><br/>
	 * <b>Description:</b><br/>
	 * The 26-bit target address is shifted left two bits and combined with the<br/>
	 * high-order bits of the address of the delay slot. The program<br/>
	 * unconditionally jumps to this calculated address with a delay of one<br/>
	 * instruction.<br/><br/> 
	 * <b>Operation:</b><br/>
	 * T: temp &larr; target<br/>
	 * T+1: PC &larr; PC<sub>31&hellip;28</sub> || temp || 0<sup>2</sup>
	 */
	@Override
	public final void execute(final int instruction) {
		
		final int target = (instruction & 0x03FFFFFF) << 2;
		
		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = (mips.R4300i.nPC & 0xF0000000) | target;

		if(Main.tracing) {
			mips.R4300i.targets.put(mips.R4300i.nPC,null);
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {

		final int target = (instruction & 0x03FFFFFF) << 2;
		
		return 	"		mips.CPU.PC = mips.CPU.nPC;\n" + 
				"		mips.CPU.nPC = (mips.CPU.nPC & 0xF0000000) | "+String.format("0x%08X",target)+";\n";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}